# -*- coding: utf-8 -*-
from micolog_plugin import *
import datetime,logging,re
from google.appengine.api import urlfetch
'''
Created on 2010-7-1

@author: 火中仙
'''

class today_history(Plugin):
    def __init__(self):
        Plugin.__init__(self,__file__)
        self.author="Fred"
        self.authoruri="mailto:me@fengsage.com"
        self.uri="http://fengsageblog.appspot.com"
        self.description="历史上的今天"
        self.name="TodayHistory"
        self.version="0.1"
        self.register_filter('history',self.getTodayHistory)

    def getTodayHistory(self,page=None,*arg1,**arg2):
        month = datetime.date.today().month
        day = datetime.date.today().day
        
        month_list = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
        if day<10: day = '0%s'%day
        
        url = u'http://www.guxiang.com/lishi/others/jintian/%s/%s.htm'%(month_list[month-1],str(day))
        
        html = self.readPage(url).replace('<br>','')
        REG_STR = u'<a href="../../../../([^>]*)" target="_blank">([^/]*)</a>'
        
        
        list = re.findall(REG_STR, html)
        
        if list:
            return self.render_content("today_history.html",{'list':list[:10]})
        else:
            return self.render_content("today_history.html")

    def readPage(self,url):
        '''
            Page reader
        '''
        logging.info('Read page:%s'%url)
        
        header = { 'Host':'hi.baidu.com',\
                   'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-CN; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9',\
                   'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\
                   'Accept-Language':'zh-cn,zh;q=0.5'}
        
        
        try:
            response = urlfetch.fetch(url=url,headers=header)
            
        except:
            logging.error('open exception')
            return 0
        if response.status_code == 200:
            html_content = response.content.replace('&nbsp;','').decode('gb2312') #baidu use GBK encode
        return html_content
